<?php

namespace App\Http\Controllers;

use App\Http\Lib\isAdmin;
use App\Models\Files;
use App\Models\Flows;
use App\Models\messages;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Lib\ResBase;
use function PHPUnit\Framework\isEmpty;

class FlowController extends Controller
{
    //通过id筛选流程列表
    public function getFlowList(Request $request){
        $id = $request->input('userId');
        $userres = isAdmin::isadmin($id);
        if($userres){
            return $userres;
        }
        if(!$id){
            return ResBase::ApiRes(401,'请输入用户id','failed');
        } else {
            try {
                $res = Flows::where('initiator',$id)->orderBy('created_at','desc')->get();
//            var_dump($res);
                if(isEmpty($res)){
                    return ResBase::ApiRes(201,'当前用户暂无审批数据');
                } else {
                    return ResBase::ApiRes(200,$res);
                }
            } catch (\Exception $e){
                return ResBase::ApiRes(400,$e->getMessage(),'failed');
            }
        }
    }
    //按序筛选流程列表
    public function getOrderFlowList(Request $request){
        $id = $request->input('userId');
        $userres = isAdmin::isadmin($id);
        if($userres){
            return $userres;
        }
        $allow = $request->input('allow');//默认未通过在前 未批：0 已批：1
        $time = $request->input('time');//默认降序 降序：0 升序：1
        $sort = ['desc','asc'];
        if(!$id || !$allow || !$time){
            return ResBase::ApiRes(401,'缺少参数','failed');
        }
        try {
            @$res = Flows::where('initiator',$id)->orderBy('created_at',$sort[$time])->orderBy('status', $sort[$allow])->get();
            if(isEmpty($res)){
                return ResBase::ApiRes(201,'当前用户暂无流程列表');
            } else {
                return ResBase::ApiRes(200,$res);
            }
        } catch (\Exception $e){
            return ResBase::ApiRes(400,$e->getMessage(),'failed');
        }
    }
    //发起流程->发起流程在上传文件时执行->同时给管理员发通知
    //审批操作->审批后发通知
    public function check(Request $request){
        $msg='';
        $suggest = $request->input('isAgree'); // 0或1 默认null
        $id = $request->input('flowId');
        $checkerid = $request->input('checkerId'); //审批者id
        if($request->has('msg')){
            $msg = $request->input('msg');
        }
        $userres = isAdmin::isadmin($checkerid);
        if($userres){
            return $userres;
        }
        if(!$suggest){
            return ResBase::ApiRes(401,'缺少参数','failed');
        } else {
            // 设置流程状态
            try {
                @$flow = Flows::where('id',$id)->first();
                if(isEmpty($flow)){
                    return ResBase::ApiRes(404,'未找到该流程','failed');
                } else {
                    $flow->status = 1;
                    $flow->passed = $suggest;
                    $flow->approver = $checkerid;  //当前审批该流程的管理员ID
                    $res = $flow->save();
                    if($res){
                        $fileid = $flow->file; //当前被审批的id
                        @$file = Files::where('id',$fileid)->first();
                        if(isEmpty($file)){
                            return ResBase::ApiRes(402,'文件不存在','failed');
                        } else {
                            $file->status = 1;
                            $file->allow = $suggest;
                            @$fres = $file->save();
                            if($fres){
                                // 回执消息
                                $msgres = messages::create([
                                    'name'=> Files::where('id',$file->file)->name,
                                    'content'=>'您上传的文件'.Files::where('id',$file->file)->name.'已审批完成，点击“我的流程”查看结果,'.'审批意见:'.$msg?$msg:"无".',审批人:'.Users::where('id',$checkerid)->user_name,
//                                    'sender'=> Users::where('id',$checkerid)->user_name,
                                    'sender'=> $checkerid,
                                    'getter'=>$flow->initiator,
                                    'type'=>'reply',
                                    'msg'=>$msg?$msg:""
                                ]);
                                if(!$msgres){
                                    return ResBase::ApiRes(406,'审批结果发送失败!','failed');
                                } else {
                                    return ResBase::ApiRes(200,'审批成功!');
                                }
                            } else {
                                return ResBase::ApiRes(403,'文件状态更新失败','failed');
                            }
                        }
                    } else {
                        return ResBase::ApiRes(400,'操作失败','failed');
                    }
                }
            } catch (\Exception $e){
                return ResBase::ApiRes(405,$e->getMessage(),'failed');
            }
        }
    }
    //查看管理员审批列表：默认未审批的排在前面
    public function getCheckList(Request $request){
        $userid = $request->input('userid');
        $userres = isAdmin::isadmin($userid);
        if($userres){
            return $userres;
        }
        $currentPage = $request->input('currentPage'); //当前查看的页码
        $perPage = $request->input('perPage'); //每页的数据数
        try {
            $res = Flows::orderBy('status', 'asc') //状态升序
            ->orderBy('created_at', 'desc') //日期降序
            ->get();
            $total = $res->count(); //数据总数
            $totalPage = ceil($total / $perPage); // 获取总页数
            $pageRes = $res->forPage($currentPage,$perPage);
            if(isEmpty($res)){
                return ResBase::ApiRes(201,'暂无数据');
            } else {
                return ResBase::ApiRes(200,['data'=>$pageRes->toArray(),'totalPage'=>$totalPage,'total'=>$total],);
            }
        } catch (\Exception $e){
            return ResBase::ApiRes(400,$e->getMessage(),'failed');
        }
    }
    //查看所有员工：默认管理员排在前面
    public function getAllUsers(Request $request){
        $userid = $request->input('userid');
        $currentPage = $request->input('currentPage'); //当前查看的页码
        $perPage = $request->input('perPage'); //每页的数据数
        $userres = isAdmin::isadmin($userid);
        if($userres){
            return $userres;
        }
        try {
            $res = Users::orderBy('isAdmin','desc')->get();
            if(isEmpty($res)){
                return ResBase::ApiRes(201,'暂无数据');
            }
            $total = $res->count(); //数据总数
            $totalPage = ceil($total / $perPage); // 获取总页数
            $pageRes = $res->forPage($currentPage,$perPage); //分页后的数据
            return ResBase::ApiRes(200,['data'=>$pageRes->toArray(),'total'=>$total,'totalPage'=>$totalPage]);
        } catch (\Exception $e){
            return ResBase::ApiRes(400,$e->getMessage(),'failed');
        }
    }

    //删除流程
    public function delFlow(Request $request){
        try {
            $flowid = $request->input('flowId');
            $res = Flows::where('id',$flowid)->first();
            if(isEmpty($res)){
                return ResBase::ApiRes(201,'未查找到此流程');
            } else {
                $delRes = $res->delete();
                if($delRes){
                    return ResBase::ApiRes(200,'删除成功!');
                } else {
                    return ResBase::ApiRes(400,'删除失败!','failed');
                }
            }
        } catch (\Exception $e){
            return ResBase::ApiRes(401,$e->getMessage(),'failed');
        }
    }

    //
}
